#!/usr/bin/python
# -*- coding: utf-8 -*-
# This script is used to cooperate douban_fm and google_music
# TODO improvements:
# 1. Add yahoo/baidu search
# 2. 繁体转简体，search again
# 3. embed album cover?

import re, sys, os, time, getopt
import google_music, douban_fm
import ID3
import database

# log = "./download.log"

#change the ID3
def change_ID3(mp3info, mp3_fullpath):
  try:
    id3info=ID3.ID3(mp3_fullpath)
  except:
    print 'open file error!' + mp3_fullpath
    return 1
  [id3info['TITLE'], id3info['ALBUM'], id3info['ARTIST']] = mp3info

# use wget to download mp3 file
def wget_mp3(download_url, save_path, mp3info):
  #log_file = open(log, "w+")
  #log_file.write("%s %s\n"%(download_url.encode("utf8"), save_path))
  #log_file.close()

  if os.path.isfile(save_path):
    print "<<< File already exists:", save_path
  else:
    print ">>> Download from:", download_url
    print "<<< Save to:", save_path
    exe_wgetstr='wget --timeout=30 -l 10 -c \"' + download_url + '\"'
    exe_wgetstr = exe_wgetstr.encode("utf8")
    exe_wgetstr = exe_wgetstr + ' -O \"' + save_path+'.tmp' + '\";'
    exe_mvstr = ' mv \"' + save_path+'.tmp' + '\" \"'+save_path + '\"'
    exe_str = exe_wgetstr+exe_mvstr
    print ">>> Executing:", exe_str
    os.system(exe_str)
    #change_ID3(mp3info, save_path)
    
def main(save_dir, people_id, ignore):
  if not os.path.exists(save_dir):
    os.makedirs(save_dir)
  music_array = douban_fm.get_song_list(people_id)

  for title, album, album_url in music_array:
    if ignore:
      find_method = database.ever_search_music
    else:
      find_method = database.if_found_music
    if find_method(title) == "found":
      pass
    else:
      artist = douban_fm.get_artist(album_url)
      if not artist:
        database.insert_unfound_music({title:{"album":album, "album_url": album_url}})
        continue
      else:
        mp3info=[title, album, artist]

      mp3_download_url = google_music.fetch_download_url_from_mp3info(mp3info)
      if save_dir[-1] != os.sep:
        save_dir = save_dir + os.sep
      if mp3_download_url:
        save_path = save_dir+title.strip()+"_"+album.strip()+"_"+artist.strip()+".mp3" 
        save_path = "-".join(save_path.split(" "))
        wget_mp3(mp3_download_url, save_path, mp3info)
        # music already downloaded
        if os.path.isfile(save_path):
          database.insert_found_music({title:{"album":album, "artist": artist}})
        else:
          sys.stderr.write("File %s is not downloaded completely.\n"%(save_path))
          sys.exit(2)
      else:
        #TODO add baidu/yahoo music search
        database.insert_unfound_music({title:{"album":album, "artist": artist}})
        sys.stderr.write("------Failed fetching: %s | %s | %s\n"%(mp3info[0], mp3info[1], mp3info[2]))
        # music not downloaded yet

def usage():
  print "Usage:"
  print "./main.py -p 2622514 -s \"../download\""
  print "./main.py peopleid=2622514 -s savedir=\"../download\""

if __name__ == "__main__":
  try:
    opts, args = getopt.getopt(sys.argv[1:], "hs:p:i", ["help", "savedir=", "peopleid=", "ignoreunfound"])
  except getopt.GetoptError, err:
    # print help information and exit:
    print str(err) # will print something like "option -a not recognized"
    usage()
    sys.exit(2)

  save_dir = database.get_save_path()
  people_id = database.get_douban_id()
  ignore = False
  for o, a in opts:
    if o in ("-h", "--help"):
      usage()
      sys.exit()
    elif o in ("-s", "--savedir"):
      save_dir = a
      database.set_save_path(save_dir)
    elif o in ("-p", "--peopleid="):
      people_id = int(a)
      database.set_douban_id(people_id)
    elif o in ("-i", "--ignoreunfound"):
      ignore = True
    else:
      assert False, "unhandled option"
  if people_id == 0:
    usage()
    assert False, "user id is required at least."
    sys.exit(2)
  if not save_dir:
    save_dir = "../download"
    database.set_save_path(save_dir)
    
  main(save_dir, people_id, ignore)
